var forms = document.getElementsByTagName ( "form" );
var t, l = forms.length;
var f;
var name = document.location.origin;

chrome.extension.sendRequest ( { "mode" : "load", "name" : name },
	function ( response )
	{
		var storage = response.data;

		for ( t = 0; t < l; t ++ )
		{
			f = forms [ t ];

			f.addEventListener ( "submit", function ( e ) 
				{
					var frm = e.srcElement;
					var res = _create_elems_list ( frm );
					var fields = res [ 0 ];
					var has_password = res [ 1 ];
					
					if ( has_password ) 
					{
						if ( confirm ( "Save form for: " + name + "?" ) )
						{
							chrome.extension.sendRequest ( { "mode" : "save", "name" : name, "fields" : fields } );
						}
					}
				} );

			_set_form_values ( f, storage );
		}
	} 
);

function _create_elems_list ( frm )
{
	var res = [];
	var elems, t, l, e;
	var has_password = null;

	function _add_el ( e )
	{
		var el;

		el = {};

		el [ 'name' ] = e.name;
		el [ 'id' ] = e.id;
		el [ 'value' ] = e.value;
		el [ 'checked' ] = e.checked;

		if ( e.type == "password" ) has_password = el;

		res.push ( el );
	}

	elems = frm.getElementsByTagName ( 'input' );
	l = elems.length;
	for ( t = 0; t < l; t ++ )
	{
		e = elems [ t ];
	
		if ( e.type == "hidden" ) continue;
		if ( e.type == "submit" ) continue;
		if ( e.type == "button" ) continue;

		_add_el ( e );
	}

	elems = frm.getElementsByTagName ( 'select' );
	l = elems.length;
	for ( t = 0; t < l; t ++ ) _add_el ( elems [ t ] );

	return [ res, has_password ];
}

function _set_form_values ( form, storage )
{

}
